<template>
    <el-row class="login-page">
        <el-col :span="14" class="bg"></el-col>
        <el-col :span="6" :offset="2" class="form">
            <!-- 注册表单 -->
            <el-form ref="form" size="large" autocomplete="off" :model="registerData" :rules="rules">
                <!-- 根据isRegister的值显示不同的表单标题 -->
                <el-form-item v-if="isRegister">
                    <h1>注册</h1>
                </el-form-item>
                <el-form-item v-else>
                    <h1>登录</h1>
                </el-form-item>
                <!-- 用户名输入框 -->
                <el-form-item prop="username">
                    <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
                </el-form-item>
                <!-- 密码输入框 -->
                <el-form-item prop="password">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"
                        show-password />
                </el-form-item>
                <!-- 注册表单特有的确认密码输入框 -->
                <el-form-item v-if="isRegister" prop="rePassword">
                    <el-input :prefix-icon="Lock" type="password" placeholder="请再次输入密码"
                        v-model="registerData.rePassword" show-password />
                </el-form-item>
                <!-- 登录表单特有的记住我选项和忘记密码链接 -->
                <el-form-item v-else class="flex">
                    <div class="flex">
                        <el-checkbox v-model="form.rememberMe">记住我</el-checkbox>
                        <el-link type="primary" :underline="false" @click="open">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <!-- 注册按钮 -->
                <el-form-item v-if="isRegister">
                    <el-button class="button" type="primary" auto-insert-space @click="registerBtn">
                        注册
                    </el-button>
                </el-form-item>
                <!-- 登录按钮 -->
                <el-form-item v-else>
                    <el-button class="button" type="primary" auto-insert-space @click="loginBtn">登录</el-button>
                </el-form-item>
                <!-- 注册表单特有的返回登录链接 -->
                <el-form-item v-if="isRegister" class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = false">
                        ← 返回
                    </el-link>
                </el-form-item>
                <!-- 登录表单特有的切换到注册链接 -->
                <el-form-item v-else class="flex">
                    <el-link type="info" :underline="false" @click="isRegister = true">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>


<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage, ElNotification } from 'element-plus'
import { reactive, ref, toRefs, getCurrentInstance } from 'vue'
import { login, register } from '@/api/user'
import { useRouter } from 'vue-router'
import { setToken, removeToken, getToken } from '@/store/token'
// 引入js-cookie库用于操作cookies
import Cookies from "js-cookie";

// 获取当前实例的代理对象
const { proxy } = getCurrentInstance();

// 获取路由实例
const router = useRouter();

// 控制是否显示注册表单，初始值为false，即默认显示登录表单
const isRegister = ref(false)

// 注册表单的数据
const registerData = ref({
    username: '',
    password: '',
    rePassword: ''
})

// 表单实例
const form = ref({
    username: "",
    password: "",
    rePassword: '',
    rememberMe: false
})

// 表单校验规则

const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== registerData.value.password) {
        callback(new Error("两次输入的密码不一致"))
    } else {
        callback()
    }
}

const data = reactive({
    rules: {
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        rePassword: [
            { required: true, message: '请再次输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 10 个字符', trigger: 'blur' },
            {
                validator: validatePass, trigger: 'blur'
            }
        ]
    }
})
// 将校验规则暴露出去
const { rules } = toRefs(data);

// 注册函数
function registerBtn() {
    proxy.$refs.form.validate(valid => {
        if (valid) {
            register(registerData.value).then(res => {
                ElMessage.success(res.msg)
                // 注册成功后，重定向到登录页面
                isRegister.value = false
                router.push('/login')
            })
        }
    })
}
// 登录函数
function loginBtn() {
    proxy.$refs.form.validate(valid => {
        if (valid) {
            // 如果选择了记住密码，则将用户名和加密后的密码以及记住密码的状态保存到cookie中
            if (form.value.rememberMe) {
                Cookies.set("username", form.value.username, { expires: 30 });
                Cookies.set("rememberMe", form.value.rememberMe, { expires: 30 });
            } else {
                // 否则，从cookie中移除相关数据
                Cookies.remove("username");
                Cookies.remove("rememberMe");
            }
            login(registerData.value).then(res => {
                ElMessage.success(res.msg)
                setToken(res.data)
                router.push('/')
            })
        }
    })
}

//忘记密码
function open() {
    ElNotification({
        title: '提示',
        message: '请联系管理员',
        type: 'warning',
        duration: 0,
        offset: 200,
    })
}
</script>


<style lang="scss" scoped>
.login-page {
    height: 100vh;
    background-color: #ffffff;
    .bg {
        background:
            /* url('@/assets/logo.png') no-repeat 60% center / 240px auto, */
            url('@/assets/login_bg.webp') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
        box-shadow: var(--el-box-shadow-dark)
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;
        
        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}
</style>